import {
  Directive,
  inject,
  input,
  TemplateRef,
  ViewContainerRef,
  effect,
} from '@angular/core';

export interface TemplateContext<T> {
  $implicit: T;
}

@Directive({
  selector: '[ngForDemo]',
  standalone: true,
})
export class NgForDemoDirective<T> {
  #tpr = inject<TemplateRef<TemplateContext<T>>>(TemplateRef);
  #vcr = inject(ViewContainerRef);

  ngForDemoOf = input.required<T[]>();

  constructor() {
    effect(() => {
      for (const item of this.ngForDemoOf()) {
        this.#vcr.createEmbeddedView(this.#tpr, {
          $implicit: item,
        });
      }
    });
  }

  static ngTemplateContextGuard<T>(
    dir: NgForDemoDirective<T>,
    ctx: any,
  ): ctx is TemplateContext<T> {
    return true;
  }
}
